package org.example.cloudalibaba.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import lombok.extern.slf4j.Slf4j;
import org.example.cloudalibaba.myhandler.MyBlockHandler;
import org.example.cloudalibaba.myhandler.MyFallbackHandler;
import org.example.springcloud.common.Result;
import org.example.springcloud.entity.Payment;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

// 使用restTemplate调用服务的PaymentService
@Slf4j
@RestController
@RequestMapping("/circuit")
public class CircuitBreakerController {
    @Resource
    private RestTemplate restTemplate;

    @Value("${service-url.nacos-user-service}")
    private String serviceUrl;

    // 调用接口：http://localhost:84/payment/get/1
    @GetMapping("/payment/get/{id}")
    @SentinelResource(value = "paymentInfo",
            fallbackClass = MyFallbackHandler.class,// 处理降级异常（java运行时异常）
            fallback = "paymentInfoFallback",
            blockHandlerClass = MyBlockHandler.class,// 处理限流异常(Sentinel控制台配置违规)
            blockHandler = "paymentInfoHandleBlock",
            exceptionsToIgnore = {IllegalArgumentException.class} // 不进行降级的异常
    )
    public Result<Payment> paymentInfo(@PathVariable("id") Long id) {
        Result<Payment> result = restTemplate.getForObject(serviceUrl + "/payment/get/" + id, Result.class, id);
        if (id == 4L) {
            log.error("非法参数异常：{}", id);
            throw new IllegalArgumentException("非法参数异常");
        } else if (result.getData() == (null)) {
            log.error("无id记录：{}", id);
            throw new NullPointerException("无id记录");
        }
        return result;
    }
}
